package com.csu.csumall.service.imp;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.csu.csumall.common.CartStatus;
import com.csu.csumall.common.ItemStatus;
import com.csu.csumall.entity.Cart;
import com.csu.csumall.mapper.CartMapper;
import com.csu.csumall.service.ICartService;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service("cartService")
public class CartServiceImp extends ServiceImpl<CartMapper, Cart> implements ICartService {

    private final CartMapper cartMapper;

    public CartServiceImp(CartMapper cartMapper) {
        this.cartMapper = cartMapper;
    }


    @Override
    public boolean addRecord(Cart cart) {

        if (null == cart.getProductId()) {
            return false;
        }

        QueryWrapper<Cart> cartQueryWrapper = new QueryWrapper<Cart>()
                .eq("product_id", cart.getProductId())
                .eq("user_id", cart.getUserId())
                .eq("status", ItemStatus.ENABLE.getValue());

        // 看之前购物车有没有这个商品
        int count = this.count(cartQueryWrapper);

        // 预处理
        LocalDateTime localDateTime = LocalDateTime.now();
        cart.setUpdateTime(localDateTime);
        if (count == 0) {
            cart.setStatus(ItemStatus.ENABLE.getValue());
            cart.setCreateTime(localDateTime);
        } else {
            // 有，先获取之前的数量
            Cart cartOld = this.getOne(cartQueryWrapper);
            Integer id = cartOld.getId();
            Integer quantity = cartOld.getQuantity();
            cart.setId(id);
            cart.setQuantity(quantity + 1);
        }
        return this.saveOrUpdate(cart);
    }

    @Override
    public int checkAll(Integer userId) {
        Cart cart = new Cart();
        cart.setChecked(CartStatus.CHECKED.getValue());
        int count = cartMapper.update(cart, new QueryWrapper<Cart>().eq("user_id", userId));
        return count;
    }

    @Override
    public int unCheckAll(Integer userId) {
        Cart cart = new Cart();
        cart.setChecked(CartStatus.UNCHECKED.getValue());
        int count = cartMapper.update(cart, new QueryWrapper<Cart>().eq("user_id", userId));
        return count;
    }
}
